package com.hnblc.blcwms.rest.controller;

import com.fasterxml.jackson.core.type.TypeReference;
import com.hnblc.blcwms.common.constant.StringPool;
import com.hnblc.blcwms.common.exceptions.ErrorDescription;
import com.hnblc.blcwms.common.exceptions.GeneralException;
import com.hnblc.blcwms.common.interaction.Response;
import com.hnblc.blcwms.common.interaction.RestResponse;
import com.hnblc.blcwms.common.utils.encrypt.BASE64;
import com.hnblc.blcwms.persistent.interfaces.business.dto.StockParam;
import com.hnblc.blcwms.persistent.interfaces.business.dto.StockQuery;
import com.hnblc.blcwms.persistent.interfaces.business.entity.SalableStock;
import com.hnblc.blcwms.persistent.interfaces.client.dto.CurrentClient;
import com.hnblc.blcwms.persistent.interfaces.client.entity.ClientAuth;
import com.hnblc.blcwms.rest.dto.restInteraction.EncryptRequest;
import com.hnblc.blcwms.serviceapi.api.dto.WareHouseOperate;
import com.hnblc.blcwms.serviceapi.api.group.owner.OwnerGroup;
import com.hnblc.blcwms.serviceapi.api.service.IStockAPIService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;
import java.util.List;

@Setter
@Getter
@RestController
@RequestMapping("blc/wms/api/stock")
@Api(value="库存查询REST API",tags={"库存接口"})
public class StockRestAPI extends BaseRestAPI {


    public static Logger logger = LoggerFactory.getLogger(StockRestAPI.class);

    @Autowired
    Validator validator;
    @Autowired
    IStockAPIService stockAPIService;

    /*@RequestMapping(value = "/list",method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParam()
    public RestResponse<ArticleStock> getStockData(@RequestBody ReadableRequest<StockHisQuery> request) throws Exception {
        RestResponse res = new RestResponse(true);
//        CurrentClient clientInfo = this.clientAuthValidation(request);
//        if (null == clientInfo) {
//            res.initError(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
//            return res;
//        }
//        List<StockHisQuery> stockDtos = objectMapper.convertValue(Base64Utils.decode(request.getBusinessData()), List.class);
//        res.setResContent(stockService.ListArticleStock(request.getBusinessData()));

        return res;
    }*/

    @ApiOperation(value="库存查询接口（加签）", notes="根据货主或商品ID查询出指定商品的库存",position = 3)
    @RequestMapping(value = "/salable" ,method = RequestMethod.POST)
    @ResponseBody
    public RestResponse<List<SalableStock>> securityQuery(@Validated({OwnerGroup.class}) @RequestBody EncryptRequest message, HttpServletRequest request) {


        //解析业务数据 从BASE64字符串解析为JSON字符串，再解析为业务对象
        WareHouseOperate<List<StockQuery>> businessData;
        try {
            businessData = objectMapper.readValue(new String(BASE64.decryptBASE64(message.getBusinessData()), StringPool.CHARSET_UTF8),new TypeReference<WareHouseOperate<List<StockQuery>>>() { });
        }catch (Exception e){
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_BAD_PARAMETER_FORMAT_0,e));
        }

        validator.validate(businessData,OwnerGroup.class);
        //校验操作权限
        ClientAuth clientAuth = this.buildAuth(message,businessData);
        //货主权限，客户专用位
        clientAuth.setCustomNo("N");
        CurrentClient currentClient = this.clientInfoService.loadCurrentClient(clientAuth);
        if (null == currentClient || currentClient.getClientAuthInfo().size() < 1) {
            return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_CLIENT_UNAUTHORIZED_0));
        }
        //验签
        try {
            if (!this.signatureValidate(message, currentClient)) {
                return new RestResponse<>(new GeneralException(ErrorDescription.ERROR_REQUEST_SIGNATURE_VALIDATE_FAIL_0));
            }
        } catch (Exception e) {
            logger.error("接口处理验签异常", e);
            throw new GeneralException(e);
        }

        StockParam stockparam = new StockParam();
        stockparam.setEnterpriseNo(clientAuth.getEnterpriseNo());
        stockparam.setWarehouseNo(clientAuth.getWarehouseNo());
        stockparam.setOwnerNo(clientAuth.getOwnerNo());
        stockparam.setArticles(businessData.getOperateDetails());
        Response<List<SalableStock>> result= stockAPIService.getSalableStocks(stockparam);
        return new RestResponse<>(result);
    }
}
